<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

/**
* This library assumes that you have already loaded the default CI Upload Library seperately
* 
* Functions is based upon CI_Upload, Feel free to modify this 
*   library to function as an extension to CI_Upload
* 
* Library modified by: Alvin Mites
* http://www.mitesdesign.com
* 
*/

class Multi_upload  {
	
	var $error_pic		= array();
	var $success_files 	= array();
	
	function Multi_upload () {}
	/**
	 * Perform multiple file uploads
     * Based upon JQuery Multiple Upload Class
     * see http://www.fyneworks.com/jquery/multiple-file-upload/
	 */	
	function go_upload($field = 'userfile') {
        $CI =& get_instance(); 
		$file_list 		= array();
        $error_hold 	= array();
//        $error_upload 	= FALSE;
        
//		检验分类是否存在
		$category_id = $CI->input->post('category_id');
		if (empty($category_id) || intval($category_id) < 1)
		{
			$error_hold[0] = 'upload_no_category_selected';
			$this->set_error($error_hold);
			return FALSE;
		}
		
		if ( ! isset($_FILES[$field]['name'][0]))
		{
			$error_hold[0] = 'upload_no_file_selected';
			$this->set_error($error_hold);
			return FALSE;
		}
		
		$num_files 		= count($_FILES[$field]['name']) -1;
		    
//      加载相册model
		$CI->load->model('galleries/gallery_m', 'gallery');

//		验证上传图片数
		$total = 0;
		$upload_max = intval($CI->settings->get('posts_per_user'));
		
		if(intval($total) >= $upload_max){
			$error_hold[0] = 'upload_count_exceed';
			$this->set_error($error_hold);
			return FALSE;
		}
		
        // Is the upload path valid?
        if ( ! $CI->upload->validate_upload_path())
        {
            // errors will already be set by validate_upload_path() so just return FALSE
            return FALSE;
        }

        for ($i=0; $i <= $num_files; $i++) {
            
//            $error_hold[$i] = FALSE;
                        
            // Was the file able to be uploaded? If not, determine the reason why.
            if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$i]))
            {
                $error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];

                switch($error)
                {
                    case 1:  // UPLOAD_ERR_INI_SIZE
                        $error_hold[$i] = 'upload_file_exceeds_limit';
                        break;
                    case 2: // UPLOAD_ERR_FORM_SIZE
                        $error_hold[$i] = 'upload_file_exceeds_form_limit';
                        break;
                    case 3: // UPLOAD_ERR_PARTIAL
                       $error_hold[$i] = 'upload_file_partial';
                        break;
                    case 4: // UPLOAD_ERR_NO_FILE
                       $error_hold[$i] = 'upload_no_file_selected';
                        break;
                    case 6: // UPLOAD_ERR_NO_TMP_DIR
                        $error_hold[$i] = 'upload_no_temp_directory';
                        break;
                    case 7: // UPLOAD_ERR_CANT_WRITE
                        $error_hold[$i] = 'upload_unable_to_write_file';
                        break;
                    case 8: // UPLOAD_ERR_EXTENSION
                        $error_hold[$i] = 'upload_stopped_by_extension';
                        break;
                    default :
                        $error_hold[$i] = 'upload_no_file_selected';
                        break;
                }

                return FALSE;
            }

            // Set the uploaded data as class variables
            $CI->upload->file_temp = $_FILES[$field]['tmp_name'][$i];        
            $CI->upload->file_name = $CI->upload->_prep_filename($_FILES[$field]['name'][$i]);
            $CI->upload->file_size = $_FILES[$field]['size'][$i];        
            $CI->upload->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$i]);
            $CI->upload->file_type = strtolower($CI->upload->file_type);
            $CI->upload->file_ext  = $CI->upload->get_extension($_FILES[$field]['name'][$i]);
            
            // Convert the file size to kilobytes
            if ($CI->upload->file_size > 0)
            {
                $CI->upload->file_size = round($CI->upload->file_size/1024, 2);
            }

            // Is the file type allowed to be uploaded?
            if ( ! $CI->upload->is_allowed_filetype())
            {
                $error_hold[$i] = 'upload_invalid_filetype';
            }

            // Is the file size within the allowed maximum?
            if ( ! $CI->upload->is_allowed_filesize())
            {
                $error_hold[$i] = 'upload_invalid_filesize';
            }

            // Are the image dimensions within the allowed size?
            // Note: This can fail if the server has an open_basdir restriction.
            if ( ! $CI->upload->is_allowed_dimensions())
            {
                $error_hold[$i] = 'upload_invalid_dimensions';
            }

            // Sanitize the file name for security
            $CI->upload->file_name = $CI->upload->clean_file_name($CI->upload->file_name);

            // Remove white spaces in the name
            if ($CI->upload->remove_spaces == TRUE)
            {
                $CI->upload->file_name = preg_replace("/\s+/", "_", $CI->upload->file_name);
            }

            /*
             * Validate the file name
             * This function appends an number onto the end of
             * the file if one with the same name already exists.
             * If it returns false there was a problem.
             */
            $CI->upload->orig_name = $CI->upload->file_name;

            if ($CI->upload->overwrite == FALSE)
            {
                $CI->upload->file_name = $CI->upload->set_filename($CI->upload->upload_path, $CI->upload->file_name);
                
                if ($CI->upload->file_name === FALSE)
                {
//                    $error_hold[$i] = TRUE;
                }
            }
            
//			创建图片日期文件夹      格式为2010-10/10/
			$current_time = time();
			$folder_year_month = $CI->upload->upload_path.date('Y-m/',$current_time);
			$folder_day = $folder_year_month.date('d/',$current_time);
			
			if(!file_exists($folder_year_month))
			{
				mkdir($folder_year_month, 0777);
			}
			if(!file_exists($folder_day))
			{
				mkdir($folder_day, 0777);
			}
//			验证上传图片上限
	        if(intval($total++) >= $upload_max){
				$error_hold[$i] = 'upload_count_exceed';
				$this->error_pic[$i]	= $CI->upload->file_name;
				continue;
			}
//          添加相册数据
			$gallery_info = $CI->gallery->create_gallery($CI->upload->file_name);
			extract($gallery_info);
			
//			添加分类数据
        	$category_id = $CI->input->post('category_id');

			$CI->gallery->add_gallery_to_category($gallery_id, $category_id);
			
            /*
             * Move the file to the final destination
             * To deal with different server configurations
             * we'll attempt to use copy() first.  If that fails
             * we'll use move_uploaded_file().  One of the two should
             * reliably work in most environments
             */
            if ( ! @copy($CI->upload->file_temp, $CI->upload->upload_path.$gallery_path))
            {
                if ( ! @move_uploaded_file($CI->upload->file_temp, $CI->upload->upload_path.$gallery_path))
                {
                     $error_hold[$i] = 'upload_destination_error';
                }
            }
            
            /*
             * Run the file through the XSS hacking filter
             * This helps prevent malicious code from being
             * embedded within a file.  Scripts can easily
             * be disguised as images or other file types.
             */
            if ($CI->upload->xss_clean == TRUE)
            {
                $CI->upload->do_xss_clean();
            }
            
            if (isset($error_hold[$i])) 
            {
//                $error_upload	= TRUE;
                $this->error_pic[$i]	= $CI->upload->file_name;
                $CI->gallery->delete_gallery($gallery_id);
                
                //$total = $total - 1;
            } 
            else 
            {
//                生成三张缩略图,后缀分别为"small.jpg   medium.jpg  large.jpg"
				resize_image($CI->upload->upload_path.$gallery_path,
					$CI->upload->upload_path. $gallery_path. '.small.jpg',
					$CI->settings->get('thumb_small_width'),
					$CI->settings->get('thumb_small_height'),
					false
				);
				/*resize_image($CI->upload->upload_path.$gallery_path,
					$CI->upload->upload_path. $gallery_path. '.medium.jpg',
					$CI->settings->get('thumb_medium_width'),
					$CI->settings->get('thumb_medium_height'),
					false
				);*/
				resize_image($CI->upload->upload_path.$gallery_path,
					$CI->upload->upload_path. $gallery_path. '.large.jpg',
					$CI->settings->get('thumb_large_width'),
					$CI->settings->get('thumb_large_height'),
					false
				);
				
                if ($imageVar = $this->multiple_image_properties($CI->upload->upload_path.$CI->upload->file_name)) {

                    $file_list[] = array(
                            'id' 		=> $gallery_id,
                            'name' 		=> $CI->upload->file_name,
                            'category' 	=> $category_id,
                            'path' 		=> $gallery_url_path,
                            'size' 		=> $CI->upload->file_size,
                            'ext' 		=> $CI->upload->file_ext,
                            'type' 		=> $imageVar->image_type,
                            'height' 	=> $imageVar->height,
                            'width' 	=> $imageVar->width
                            );
                } else {
                    $file_list[] = array(
                            'id' 		=> $gallery_id,
                            'name' 		=> $CI->upload->file_name,
                            'category' 	=> $category_id,
                            'path' 		=> $gallery_url_path,
                            'size' 		=> $CI->upload->file_size,
                            'type' 		=> $CI->upload->file_type,
                            'ext'  		=> $CI->upload->file_ext,
                            );
                }
            }
        } // end for loop

        $this->set_error($error_hold);
        $this->success_files = $file_list;
    }
	function go_edit_upload($gallery_info, $field = 'userfile') {
        $CI =& get_instance(); 
		$file_list 		= array();
        $error_hold 	= array();
		
		if ( ! isset($_FILES[$field]['name']))
		{
			$error_hold[0] = 'upload_no_file_selected';
			$this->set_error($error_hold);
			return FALSE;
		}
		
		$num_files 		= count($_FILES[$field]['name']) -1;
		    
//      加载相册model
		$CI->load->model('galleries/gallery_m', 'gallery');

        // Is the upload path valid?
        if ( ! $CI->upload->validate_upload_path())
        {
            // errors will already be set by validate_upload_path() so just return FALSE
            return FALSE;
        }

            // Was the file able to be uploaded? If not, determine the reason why.
            if ( ! is_uploaded_file($_FILES[$field]['tmp_name']))
            {
                $error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];

                switch($error)
                {
                    case 1:  // UPLOAD_ERR_INI_SIZE
                        $error_hold[0] = 'upload_file_exceeds_limit';
                        break;
                    case 2: // UPLOAD_ERR_FORM_SIZE
                        $error_hold[0] = 'upload_file_exceeds_form_limit';
                        break;
                    case 3: // UPLOAD_ERR_PARTIAL
                       $error_hold[0] = 'upload_file_partial';
                        break;
                    case 4: // UPLOAD_ERR_NO_FILE
                       $error_hold[0] = 'upload_no_file_selected';
                        break;
                    case 6: // UPLOAD_ERR_NO_TMP_DIR
                        $error_hold[0] = 'upload_no_temp_directory';
                        break;
                    case 7: // UPLOAD_ERR_CANT_WRITE
                        $error_hold[0] = 'upload_unable_to_write_file';
                        break;
                    case 8: // UPLOAD_ERR_EXTENSION
                        $error_hold[0] = 'upload_stopped_by_extension';
                        break;
                    default :
                        $error_hold[0] = 'upload_no_file_selected';
                        break;
                }

                return FALSE;
            }

            // Set the uploaded data as class variables
            $CI->upload->file_temp = $_FILES[$field]['tmp_name'];        
            $CI->upload->file_name = $CI->upload->_prep_filename($_FILES[$field]['name']);
            $CI->upload->file_size = $_FILES[$field]['size'];        
            $CI->upload->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
            $CI->upload->file_type = strtolower($CI->upload->file_type);
            $CI->upload->file_ext  = $CI->upload->get_extension($_FILES[$field]['name']);
            
            // Convert the file size to kilobytes
            if ($CI->upload->file_size > 0)
            {
                $CI->upload->file_size = round($CI->upload->file_size/1024, 2);
            }

            // Is the file type allowed to be uploaded?
            if ( ! $CI->upload->is_allowed_filetype())
            {
                $error_hold[0] = 'upload_invalid_filetype';
            }

            // Is the file size within the allowed maximum?
            if ( ! $CI->upload->is_allowed_filesize())
            {
                $error_hold[0] = 'upload_invalid_filesize';
            }

            // Are the image dimensions within the allowed size?
            // Note: This can fail if the server has an open_basdir restriction.
            if ( ! $CI->upload->is_allowed_dimensions())
            {
                $error_hold[0] = 'upload_invalid_dimensions';
            }

            // Sanitize the file name for security
            $CI->upload->file_name = $CI->upload->clean_file_name($CI->upload->file_name);

            // Remove white spaces in the name
            if ($CI->upload->remove_spaces == TRUE)
            {
                $CI->upload->file_name = preg_replace("/\s+/", "_", $CI->upload->file_name);
            }

            /*
             * Validate the file name
             * This function appends an number onto the end of
             * the file if one with the same name already exists.
             * If it returns false there was a problem.
             */
            $CI->upload->orig_name = $CI->upload->file_name;

            if ($CI->upload->overwrite == FALSE)
            {
                $CI->upload->file_name = $CI->upload->set_filename($CI->upload->upload_path, $CI->upload->file_name);
                
                if ($CI->upload->file_name === FALSE)
                {
//                    $error_hold[$i] = TRUE;
                }
            }
			
			$gallery_id = $gallery_info->id;
			$gallery_path = $gallery_info->path;
			$gallery_url_path = site_url('uploads/'.$gallery_path);
            /*
             * Move the file to the final destination
             * To deal with different server configurations
             * we'll attempt to use copy() first.  If that fails
             * we'll use move_uploaded_file().  One of the two should
             * reliably work in most environments
             */
            if ( ! @copy($CI->upload->file_temp, $CI->upload->upload_path.$gallery_path))
            {
                if ( ! @move_uploaded_file($CI->upload->file_temp, $CI->upload->upload_path.$gallery_path))
                {
                     $error_hold[0] = 'upload_destination_error';
                }
            }
            
            /*
             * Run the file through the XSS hacking filter
             * This helps prevent malicious code from being
             * embedded within a file.  Scripts can easily
             * be disguised as images or other file types.
             */
            if ($CI->upload->xss_clean == TRUE)
            {
                $CI->upload->do_xss_clean();
            }
            
            if (isset($error_hold[0])) 
            {
                $this->error_pic[0]	= $CI->upload->file_name;
//                $CI->gallery->delete_gallery($gallery_id);
            } 
            else 
            {
//                生成三张缩略图,后缀分别为"small.jpg   medium.jpg  large.jpg"
				resize_image($CI->upload->upload_path.$gallery_path,
					$CI->upload->upload_path. $gallery_path. '.small.jpg',
					$CI->settings->get('thumb_small_width'),
					$CI->settings->get('thumb_small_height'),
					false
				);
				/*resize_image($CI->upload->upload_path.$gallery_path,
					$CI->upload->upload_path. $gallery_path. '.medium.jpg',
					$CI->settings->get('thumb_medium_width'),
					$CI->settings->get('thumb_medium_height'),
					false
				);*/
				resize_image($CI->upload->upload_path.$gallery_path,
					$CI->upload->upload_path. $gallery_path. '.large.jpg',
					$CI->settings->get('thumb_large_width'),
					$CI->settings->get('thumb_large_height'),
					false
				);
				
                if ($imageVar = $this->multiple_image_properties($CI->upload->upload_path.$CI->upload->file_name)) {

                    $file_list[] = array(
                            'id' 		=> $gallery_id,
                            'name' 		=> $CI->upload->file_name,
                            'path' 		=> $gallery_url_path,
                            'size' 		=> $CI->upload->file_size,
                            'ext' 		=> $CI->upload->file_ext,
                            'type' 		=> $imageVar->image_type,
                            'height' 	=> $imageVar->height,
                            'width' 	=> $imageVar->width
                            );
                } else {
                    $file_list[] = array(
                            'id' 		=> $gallery_id,
                            'name' 		=> $CI->upload->file_name,
                            'path' 		=> $gallery_url_path,
                            'size' 		=> $CI->upload->file_size,
                            'type' 		=> $CI->upload->file_type,
                            'ext'  		=> $CI->upload->file_ext,
                            );
                }
            }

        $this->set_error($error_hold);
        $this->success_files = $file_list;
    }
    
    // --------------------------------------------------------------------

    /**
     * Set Image Properties
     *
     * Uses GD to determine the width/height/type of image
     *
     * @access    public
     * @param    string
     * @return    void
     */    
    function multiple_image_properties($path = '')
    {
        $CI =& get_instance(); 
        if ( ! $CI->upload->is_image())
        {
            return false;
        }

        if (function_exists('getimagesize'))
        {
            if (FALSE !== ($D = @getimagesize($path)))
            {    
                $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');

                $image->width       = $D['0'];
                $image->height      = $D['1'];
                $image->image_type        = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
                
                return $image;
            }
        }
    }
    

    /**
     * Set an error message
     *
     * @access    public
     * @param    string
     * @return    void
     */    
    function set_error($msg)
    {
        $CI =& get_instance();    
        $CI->lang->load('upload');
        
        if (is_array($msg))
        {
        	for ($i=0; $i <= count($msg); $i++) 
        	{
        		if(!empty($msg[$i]))
        		{
	        		$err_msg		   = ($CI->lang->line($msg[$i]) == FALSE) ? $msg[$i] : $CI->lang->line($msg[$i]); 
	                if(isset($this->error_pic[$i]))
	                {
		        		$this->error_msg[] = $this->error_pic[$i]. '--'. $err_msg;
	                }
	                else 
	                {
		        		$this->error_msg[] = $err_msg;
	                }
	                log_message('error', $err_msg);
        		}
        	}
        }
    }
    function get_errors()
    {
        if(isset($this->error_msg))
        {
	    	return $this->error_msg;
        }
        else{
        	return null;
        }
    }
    function get_success_files()
    {
    	return $this->success_files;
    }
    
}
?>
